//
//  WJUserManager.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/20.
//

import Foundation
import StoreKit

// MARK: - VIP状态枚举
enum WJVIPState: Codable {
    case nonVIP
    case vip(expireDate: Date)
    case lifetimeVIP
    
    var isVIP: Bool {
        switch self {
        case .nonVIP:
            return false
        case .vip(let expireDate):
            return Date() < expireDate
        case .lifetimeVIP:
            return true
        }
    }
}

// MARK: - 优惠资格状态
enum WJOfferEligibility {
    case eligibleForTrial // 有免费试用资格
    case eligibleForIntroOffer // 有首期优惠资格
    case notEligible // 无优惠资格
    case unknown // 未知（网络错误等情况）
}

// MARK: - 产品配置（增加试用和优惠字段）
struct WJProductConfig {
    let productId: String
    let isLifetime: Bool
    let duration: TimeInterval? // 订阅时长（秒）
    let hasTrial: Bool // 是否有免费试用
    let hasIntroOffer: Bool // 是否有首期优惠
    
    static let configs: [WJProductConfig] = [
        WJProductConfig(productId: WJSku.yearly.rawValue, isLifetime: false, duration: 365 * 24 * 60 * 60, hasTrial: false, hasIntroOffer: false),
        WJProductConfig(productId: WJSku.yearlyDiscount.rawValue, isLifetime: false, duration: 365 * 24 * 60 * 60, hasTrial: false, hasIntroOffer: false),
        WJProductConfig(productId: WJSku.weekly.rawValue, isLifetime: false, duration: 7 * 24 * 60 * 60, hasTrial: false, hasIntroOffer: false),
        WJProductConfig(productId: WJSku.weeklyFree.rawValue, isLifetime: false, duration: 7 * 24 * 60 * 60, hasTrial: true, hasIntroOffer: false),
    ]
    
    static func config(for productId: String) -> WJProductConfig? {
        return configs.first { $0.productId == productId }
    }
}

// MARK: - 用户管理类
class WJUserManager: NSObject {
    
    // MARK: - 单例
    static let shared = WJUserManager()
    
    // 已经显示过折扣
    var showedDiscountPlan: Bool {
        get {
            UserDefaults.standard.bool(forKey: showDiscountPlanKey)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: showDiscountPlanKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    // MARK: - 属性
    private(set) var vipState: WJVIPState = .nonVIP
    private let userDefaultsKey = "WJVIPStateStorage"
    private let sharedSecret = "bb8e7c6758d04ec8b93a06df50ebf3c6"
    private let showDiscountPlanKey = "showDiscountPlanKey"
    
    // 购买记录存储
    private var purchaseRecords: [PurchaseRecord] = []
    private let purchaseRecordsKey = "WJPurchaseRecords"
    
    // 优惠资格缓存
    private var offerEligibilityCache: WJOfferEligibility?
    private let offerEligibilityCacheKey = "WJOfferEligibilityCache"
    private var lastEligibilityCheckTime: Date?
    private let eligibilityCacheDuration: TimeInterval = 3600 // 1小时缓存
    
    private struct PurchaseRecord: Codable {
        let productId: String
        let purchaseDate: Date
        let transactionId: String
    }
    
    // MARK: - 初始化
    private override init() {
        super.init()
        loadVIPState()
        loadPurchaseRecords()
        loadOfferEligibilityCache()
        setupExpirationChecker()
        
        // 启动时验证VIP状态
        validateVIPStatusOnLaunch()
    }
    
    // MARK: - 公开接口
    
    /// 检查用户是否是VIP
    var isVIP: Bool {
        checkVIPExpiration()
        return vipState.isVIP
    }
    
    /// 获取VIP过期时间
    var expireDate: Date? {
        switch vipState {
        case .vip(let expireDate):
            return expireDate
        default:
            return nil
        }
    }
    
    /// 获取VIP剩余天数
    var remainingDays: Int? {
        guard let expireDate = expireDate else { return nil }
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: Date(), to: expireDate)
        return max(components.day ?? 0, 0)
    }
    
    /// 验证并设置VIP状态（核心方法）- 增强版，同时验证优惠资格
    func validateAndSetVIPStatus(receipt: String? = nil, productId: String? = nil, completion: ((Bool) -> Void)? = nil) {
        #if DEBUG
        if isUsingStoreKitTesting() {
            // StoreKit 测试环境
            handleTestEnvironment(productId: productId, completion: completion)
        } else {
            // 沙盒环境
            validateWithAppleServer(receipt ?? getReceiptData(), isSandbox: true, completion: completion)
        }
        #else
        // 生产环境
        validateWithAppleServer(receipt ?? getReceiptData(), isSandbox: false, completion: completion)
        #endif
    }
    
    /// 处理购买成功 - 增强版，清除优惠资格缓存
    func handlePurchaseSuccess(productId: String, transactionId: String, purchaseDate: Date = Date()) {
        // 保存购买记录
        let record = PurchaseRecord(productId: productId, purchaseDate: purchaseDate, transactionId: transactionId)
        purchaseRecords.append(record)
        savePurchaseRecords()
        
        // 更新VIP状态
        updateVIPStateAfterPurchase(productId: productId, purchaseDate: purchaseDate)
        
        // 清除优惠资格缓存（因为用户可能使用了优惠）
        clearOfferEligibilityCache()
        
        print("购买成功: \(productId), 交易ID: \(transactionId)")
    }
    
    func shouldShowOffer(completion: @escaping (Bool) -> Void) {
        checkOfferEligibility { eligibility in
            let shouldShow: Bool
            
            switch eligibility {
            case .eligibleForTrial, .eligibleForIntroOffer:
                // 用户有试用或首期优惠资格，应该显示优惠信息
                shouldShow = true
                
            case .notEligible, .unknown:
                // 没有优惠资格或资格未知，不显示优惠信息
                shouldShow = false
            }
            
            completion(shouldShow)
        }
    }

    /// 恢复购买 - 增强版，同时恢复优惠资格状态
    func restorePurchases(receipt: String? = nil, completion: ((Bool) -> Void)? = nil) {
        validateAndSetVIPStatus(receipt: receipt, completion: completion)
    }
    
    /// 清除VIP状态 - 增强版，同时清除优惠缓存
    func clearVIP() {
        setVIPState(.nonVIP)
        purchaseRecords.removeAll()
        savePurchaseRecords()
        clearOfferEligibilityCache()
    }
    
    // MARK: - 新增：优惠资格相关方法
    /// 检查用户是否有免费试用或首期优惠资格
    func checkOfferEligibility(completion: @escaping (WJOfferEligibility) -> Void) {
        // 检查缓存
        if let cachedEligibility = offerEligibilityCache,
           let lastCheck = lastEligibilityCheckTime,
           Date().timeIntervalSince(lastCheck) < eligibilityCacheDuration {
            completion(cachedEligibility)
            return
        }
        
        #if DEBUG
        if isUsingStoreKitTesting() {
            // 测试环境：检查本地记录
            let eligibility = checkLocalOfferEligibility()
            cacheOfferEligibility(eligibility)
            completion(eligibility)
            return
        }
        #endif
        
        // 生产/沙盒环境：验证收据
        validateOfferEligibilityWithReceipt(completion: completion)
    }
    
    /// 检查特定产品是否有优惠资格
    func checkOfferEligibilityForProduct(_ productId: String, completion: @escaping (Bool) -> Void) {
        checkOfferEligibility { eligibility in
            guard let config = WJProductConfig.config(for: productId) else {
                completion(false)
                return
            }
            
            switch eligibility {
            case .eligibleForTrial:
                completion(config.hasTrial)
            case .eligibleForIntroOffer:
                completion(config.hasIntroOffer)
            case .notEligible, .unknown:
                completion(false)
            }
        }
    }
    
    /// 获取当前优惠状态描述（用于UI显示）
    func getCurrentOfferStatusDescription(completion: @escaping (String) -> Void) {
        checkOfferEligibility { eligibility in
            let description: String
            switch eligibility {
            case .eligibleForTrial:
                description = "免费试用可用"
            case .eligibleForIntroOffer:
                description = "首期优惠可用"
            case .notEligible:
                description = "标准订阅价格"
            case .unknown:
                description = "加载中..."
            }
            completion(description)
        }
    }
    
    // MARK: - 私有方法
    
    // MARK: 环境检测
    private func isUsingStoreKitTesting() -> Bool {
        #if targetEnvironment(simulator)
        return true  // 模拟器总是测试环境
        #else
        // 真机测试：检查收据文件路径是否包含测试标识
        guard let receiptURL = Bundle.main.appStoreReceiptURL else {
            return true
        }
        return receiptURL.path.contains("StoreKit") || receiptURL.path.contains("sandboxReceipt")
        #endif
    }
    
    private func isUsingSandboxEnvironment() -> Bool {
        #if DEBUG
        return !isUsingStoreKitTesting()
        #else
        return false
        #endif
    }
    
    // MARK: 测试环境处理
    private func handleTestEnvironment(productId: String?, completion: ((Bool) -> Void)? = nil) {
        if let productId = productId {
            // 有具体产品：处理新购买
            updateVIPStateAfterPurchase(productId: productId, purchaseDate: Date())
            completion?(true)
        } else {
            // 没有产品：验证现有状态
            restoreFromLocalRecords(completion: completion)
        }
    }
    
    private func restoreFromLocalRecords(completion: ((Bool) -> Void)? = nil) {
        let validState = calculateVIPStateFromRecords()
        setVIPState(validState)
        completion?(validState.isVIP)
    }
    
    private func calculateVIPStateFromRecords() -> WJVIPState {
        var latestExpireDate: Date?
        var hasLifetime = false
        
        for record in purchaseRecords {
            guard let config = WJProductConfig.config(for: record.productId) else { continue }
            
            if config.isLifetime {
                hasLifetime = true
                break
            } else if let duration = config.duration {
                let expireDate = record.purchaseDate.addingTimeInterval(duration)
                if Date() < expireDate {
                    if let currentLatest = latestExpireDate {
                        if expireDate > currentLatest {
                            latestExpireDate = expireDate
                        }
                    } else {
                        latestExpireDate = expireDate
                    }
                }
            }
        }
        
        if hasLifetime {
            return .lifetimeVIP
        } else if let expireDate = latestExpireDate {
            return .vip(expireDate: expireDate)
        } else {
            return .nonVIP
        }
    }
    
    private func updateVIPStateAfterPurchase(productId: String, purchaseDate: Date) {
        guard let config = WJProductConfig.config(for: productId) else {
            setVIPState(.nonVIP)
            return
        }
        
        if config.isLifetime {
            setVIPState(.lifetimeVIP)
        } else if let duration = config.duration {
            let expireDate = purchaseDate.addingTimeInterval(duration)
            setVIPState(.vip(expireDate: expireDate))
        } else {
            setVIPState(.nonVIP)
        }
    }
    
    // MARK: 生产环境验证
    private func validateWithAppleServer(_ receipt: String?, isSandbox: Bool, completion: ((Bool) -> Void)? = nil) {
        guard let receipt = receipt else {
            // 没有收据，使用本地记录
            let state = calculateVIPStateFromRecords()
            setVIPState(state)
            completion?(state.isVIP)
            return
        }
        
        let urlString = isSandbox ?
            "https://sandbox.itunes.apple.com/verifyReceipt" :
            "https://buy.itunes.apple.com/verifyReceipt"
        
        guard let url = URL(string: urlString),
              let requestData = try? JSONSerialization.data(withJSONObject: [
                "receipt-data": receipt,
                "password": sharedSecret,
                "exclude-old-transactions": false
              ]) else {
            // 请求创建失败，使用本地状态
            completion?(isVIP)
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = requestData
        request.timeoutInterval = 30
        
        let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
            guard let self = self else { return }
            
            if let error = error {
                print("收据验证网络错误: \(error)，使用本地状态")
                completion?(self.isVIP)
                return
            }
            
            guard let data = data,
                  let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
                  let status = json["status"] as? Int else {
                print("收据响应解析失败，使用本地状态")
                completion?(self.isVIP)
                return
            }
            
            if status == 0 {
                if let newState = self.parseVIPStateFromReceipt(json) {
                    self.setVIPState(newState)
                    completion?(newState.isVIP)
                } else {
                    completion?(self.isVIP)
                }
            } else {
                print("收据验证失败，状态码: \(status)")
                completion?(false)
            }
        }
        task.resume()
    }
    
    private func parseVIPStateFromReceipt(_ receiptInfo: [String: Any]) -> WJVIPState? {
        // 这里解析服务器返回的收据信息
        // 实际实现需要根据收据结构解析in_app数组
        // 简化实现：使用本地记录作为备选
        return calculateVIPStateFromRecords()
    }
    
    // MARK: 优惠资格验证
    
    /// 通过收据验证优惠资格（生产/沙盒环境）
    private func validateOfferEligibilityWithReceipt(completion: @escaping (WJOfferEligibility) -> Void) {
        guard let receiptData = getReceiptData() else {
            // 没有收据，认为是新用户（有资格）
            let eligibility: WJOfferEligibility = .eligibleForTrial
            cacheOfferEligibility(eligibility)
            completion(eligibility)
            return
        }
        
        let isSandbox = isUsingSandboxEnvironment()
        let urlString = isSandbox ?
            "https://sandbox.itunes.apple.com/verifyReceipt" :
            "https://buy.itunes.apple.com/verifyReceipt"
        
        guard let url = URL(string: urlString),
              let requestData = try? JSONSerialization.data(withJSONObject: [
                "receipt-data": receiptData,
                "password": sharedSecret,
                "exclude-old-transactions": false
              ]) else {
            let eligibility: WJOfferEligibility = .unknown
            cacheOfferEligibility(eligibility)
            completion(eligibility)
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = requestData
        request.timeoutInterval = 30
        
        let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
            guard let self = self else { return }
            
            if let error = error {
                print("优惠资格验证网络错误: \(error)")
                let eligibility: WJOfferEligibility = .unknown
                self.cacheOfferEligibility(eligibility)
                completion(eligibility)
                return
            }
            
            guard let data = data,
                  let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
                  let status = json["status"] as? Int, status == 0 else {
                let eligibility: WJOfferEligibility = .unknown
                self.cacheOfferEligibility(eligibility)
                completion(eligibility)
                return
            }
            
            let eligibility = self.parseOfferEligibilityFromReceipt(json)
            self.cacheOfferEligibility(eligibility)
            completion(eligibility)
        }
        task.resume()
    }
    
    /// 从收据中解析优惠资格
    private func parseOfferEligibilityFromReceipt(_ receiptInfo: [String: Any]) -> WJOfferEligibility {
        guard let receipt = receiptInfo["receipt"] as? [String: Any],
              let inAppPurchases = receipt["in_app"] as? [[String: Any]] else {
            return .eligibleForTrial // 没有购买记录，认为有资格
        }
        
        var hasEverUsedTrial = false
        var hasEverUsedIntroOffer = false
        var hasActiveSubscription = false
        
        for purchaseDict in inAppPurchases {
            // 检查是否有过试用
            if let isTrialPeriod = purchaseDict["is_trial_period"] as? String,
               isTrialPeriod.lowercased() == "true" {
                hasEverUsedTrial = true
            }
            
            // 检查是否有过首期优惠
            if let isInIntroOfferPeriod = purchaseDict["is_in_intro_offer_period"] as? String,
               isInIntroOfferPeriod.lowercased() == "true" {
                hasEverUsedIntroOffer = true
            }
            
            // 检查是否有有效订阅
            if let expiresDateMs = purchaseDict["expires_date_ms"] as? String,
               let timeInterval = TimeInterval(expiresDateMs) {
                let expiresDate = Date(timeIntervalSince1970: timeInterval / 1000)
                if Date() < expiresDate {
                    hasActiveSubscription = true
                }
            }
        }
        
        // 判断逻辑
        if hasActiveSubscription {
            // 有有效订阅，检查是否正在享受优惠
            return checkCurrentOfferStatus(inAppPurchases)
        } else {
            // 没有有效订阅，检查历史记录
            if hasEverUsedTrial || hasEverUsedIntroOffer {
                return .notEligible // 曾经使用过优惠，不再有资格
            } else {
                return .eligibleForTrial // 新用户，有试用资格
            }
        }
    }
    
    /// 检查当前是否正在享受优惠
    private func checkCurrentOfferStatus(_ inAppPurchases: [[String: Any]]) -> WJOfferEligibility {
        for purchaseDict in inAppPurchases {
            // 检查是否在试用期
            if let isTrialPeriod = purchaseDict["is_trial_period"] as? String,
               isTrialPeriod.lowercased() == "true",
               let expiresDateMs = purchaseDict["expires_date_ms"] as? String,
               let timeInterval = TimeInterval(expiresDateMs) {
                let expiresDate = Date(timeIntervalSince1970: timeInterval / 1000)
                if Date() < expiresDate {
                    return .eligibleForTrial
                }
            }
            
            // 检查是否在首期优惠期
            if let isInIntroOfferPeriod = purchaseDict["is_in_intro_offer_period"] as? String,
               isInIntroOfferPeriod.lowercased() == "true",
               let expiresDateMs = purchaseDict["expires_date_ms"] as? String,
               let timeInterval = TimeInterval(expiresDateMs) {
                let expiresDate = Date(timeIntervalSince1970: timeInterval / 1000)
                if Date() < expiresDate {
                    return .eligibleForIntroOffer
                }
            }
        }
        
        return .notEligible
    }
    
    /// 本地检查优惠资格（测试环境使用）
    private func checkLocalOfferEligibility() -> WJOfferEligibility {
        // 检查本地是否有购买记录
        if purchaseRecords.isEmpty {
            return .eligibleForTrial // 没有购买记录，有试用资格
        }
        
        // 检查是否有有效订阅
        let currentState = calculateVIPStateFromRecords()
        if currentState.isVIP {
            // 有有效订阅，检查是否是最近购买的（模拟优惠期）
            if let latestRecord = purchaseRecords.sorted(by: { $0.purchaseDate > $1.purchaseDate }).first {
                let timeSincePurchase = Date().timeIntervalSince(latestRecord.purchaseDate)
                // 假设优惠期是购买后的前7天
                if timeSincePurchase < 7 * 24 * 60 * 60 {
                    if let config = WJProductConfig.config(for: latestRecord.productId) {
                        if config.hasTrial {
                            return .eligibleForTrial
                        } else if config.hasIntroOffer {
                            return .eligibleForIntroOffer
                        }
                    }
                }
            }
            return .notEligible
        } else {
            // 没有有效订阅，检查是否有历史记录
            return .notEligible
        }
    }
    
    // MARK: 优惠资格缓存管理
    
    private func cacheOfferEligibility(_ eligibility: WJOfferEligibility) {
        offerEligibilityCache = eligibility
        lastEligibilityCheckTime = Date()
        saveOfferEligibilityCache()
    }
    
    private func clearOfferEligibilityCache() {
        offerEligibilityCache = nil
        lastEligibilityCheckTime = nil
        UserDefaults.standard.removeObject(forKey: offerEligibilityCacheKey)
    }
    
    private func saveOfferEligibilityCache() {
        var rawValue = ""
        switch offerEligibilityCache {
        case .eligibleForTrial: rawValue = "eligibleForTrial"
        case .eligibleForIntroOffer: rawValue = "eligibleForIntroOffer"
        case .notEligible: rawValue = "notEligible"
        case .unknown: rawValue = "unknown"
        case .none: rawValue = ""
        }
        
        let cacheData: [String: Any] = [
            "eligibility": rawValue,
            "lastCheckTime": lastEligibilityCheckTime ?? Date()
        ]
        UserDefaults.standard.set(cacheData, forKey: offerEligibilityCacheKey)
    }
    
    private func loadOfferEligibilityCache() {
        if let cacheData = UserDefaults.standard.dictionary(forKey: offerEligibilityCacheKey),
           let rawValue = cacheData["eligibility"] as? String,
           let lastCheckTime = cacheData["lastCheckTime"] as? Date {
            
            switch rawValue {
            case "eligibleForTrial": offerEligibilityCache = .eligibleForTrial
            case "eligibleForIntroOffer": offerEligibilityCache = .eligibleForIntroOffer
            case "notEligible": offerEligibilityCache = .notEligible
            case "unknown": offerEligibilityCache = .unknown
            default: offerEligibilityCache = nil
            }
            lastEligibilityCheckTime = lastCheckTime
        }
    }
    
    // MARK: 数据持久化
    private func setVIPState(_ state: WJVIPState) {
        vipState = state
        saveVIPState()
    }
    
    private func saveVIPState() {
        if let encoded = try? JSONEncoder().encode(vipState) {
            UserDefaults.standard.set(encoded, forKey: userDefaultsKey)
        }
    }
    
    private func loadVIPState() {
        if let data = UserDefaults.standard.data(forKey: userDefaultsKey),
           let savedState = try? JSONDecoder().decode(WJVIPState.self, from: data) {
            self.vipState = savedState
        }
    }
    
    private func savePurchaseRecords() {
        if let encoded = try? JSONEncoder().encode(purchaseRecords) {
            UserDefaults.standard.set(encoded, forKey: purchaseRecordsKey)
        }
    }
    
    private func loadPurchaseRecords() {
        if let data = UserDefaults.standard.data(forKey: purchaseRecordsKey),
           let records = try? JSONDecoder().decode([PurchaseRecord].self, from: data) {
            self.purchaseRecords = records
        }
    }
    
    // MARK: 收据获取
    private func getReceiptData() -> String? {
        guard let receiptURL = Bundle.main.appStoreReceiptURL,
              let receiptData = try? Data(contentsOf: receiptURL) else {
            return nil
        }
        return receiptData.base64EncodedString()
    }
    
    // MARK: 过期检查
    private func checkVIPExpiration() {
        if case .vip(let expireDate) = vipState {
            if Date() >= expireDate {
                setVIPState(.nonVIP)
                print("VIP已过期")
            }
        }
    }
    
    private func setupExpirationChecker() {
        Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
            self?.checkVIPExpiration()
        }
    }
    
    private func validateVIPStatusOnLaunch() {
        validateAndSetVIPStatus { isVIP in
            print("启动验证完成: VIP状态 - \(isVIP)")
        }
    }
    
    // MARK: - 调试方法
    func printVIPStatus() {
        switch vipState {
        case .nonVIP:
            print("当前状态: 非VIP用户")
        case .vip(let expireDate):
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            print("当前状态: VIP用户")
            print("过期时间: \(formatter.string(from: expireDate))")
            print("剩余天数: \(remainingDays ?? 0)天")
        case .lifetimeVIP:
            print("当前状态: 永久VIP用户")
        }
        
        // 打印优惠资格状态
        if let eligibility = offerEligibilityCache {
            let eligibilityText: String
            switch eligibility {
            case .eligibleForTrial: eligibilityText = "有免费试用资格"
            case .eligibleForIntroOffer: eligibilityText = "有首期优惠资格"
            case .notEligible: eligibilityText = "无优惠资格"
            case .unknown: eligibilityText = "资格未知"
            }
            print("优惠资格: \(eligibilityText)")
        }
    }
    
    func printPurchaseRecords() {
        print("购买记录数量: \(purchaseRecords.count)")
        for record in purchaseRecords {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            print("- 产品: \(record.productId), 时间: \(formatter.string(from: record.purchaseDate))")
        }
    }
    
    func getIntroductoryPriceDurationInDays(product: SKProduct) -> Int? {
        // 检查是否存在介绍性价格
        guard let introductoryPrice = product.introductoryPrice else {
            return nil
        }
        
        let subscriptionPeriod = introductoryPrice.subscriptionPeriod
        let numberOfUnits = subscriptionPeriod.numberOfUnits
        let unit = subscriptionPeriod.unit
        
        // 根据单位计算估算天数
        switch unit {
        case .day:
            return numberOfUnits
        case .week:
            return numberOfUnits * 7
        case .month:
            return numberOfUnits * 30 // 近似值
        case .year:
            return numberOfUnits * 365 // 近似值
        @unknown default:
            return nil
        }
    }
}
